package cn.tedu._05article.controller;

import cn.tedu._05article.base.response.JsonResult;
import cn.tedu._05article.base.response.StatusCode;
import cn.tedu._05article.mapper.UserMapper;
import cn.tedu._05article.pojo.dto.UserArticleParam;
import cn.tedu._05article.pojo.dto.UserloginParam;
import cn.tedu._05article.pojo.entity.Article;
import cn.tedu._05article.pojo.vo.ArticleVO;
import cn.tedu._05article.pojo.vo.UserVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


@Slf4j
@RestController
@Tag(name = "02-用户登录模块")
@RequestMapping("v1/user/")

public class UserController {
    @Autowired
    private UserMapper userMapper;

    @PostMapping("login")
    @Operation(summary = "用户登录")
    @ApiOperationSupport(order = 10)
    public JsonResult login(@Validated @RequestBody UserloginParam userloginParam, HttpSession session) {
        log.debug("userloginParam =" + userloginParam);
        UserVO  userVO = userMapper.selectByUsernameAndPassword(userloginParam);
        if (userVO == null) {
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        }
        session.setAttribute("user",  userVO);
        return JsonResult.ok(userVO);
    }

    @PostMapping("article")
    @Operation(summary = "用户发布文章")
    @ApiOperationSupport(order = 20)
    public JsonResult addArticle(@Validated @RequestBody UserArticleParam userArticleParam , HttpSession session) {
        log.debug("userArticleParam =" + userArticleParam);
        UserVO  userVO = (UserVO) session.getAttribute("user");
        log.debug("userVO =" + userVO);
//        if (userVO == null) {
//            return new JsonResult(StatusCode.NOT_LOGIN);
//        }
        Article  article = new Article();
        BeanUtils.copyProperties(userArticleParam, article);
        article.setUserId(userVO.getId());
        userMapper.insertArticle(article);
        return JsonResult.ok();
    }

    @GetMapping("selectByArticleId")
    @Operation(summary = "根据文章id查询文章")
    @ApiOperationSupport(order = 2)
    public JsonResult selectByArticleId(@Validated  Long articleId) {
        log.debug("articleId = " + articleId);
        ArticleVO articleVO = userMapper.selectByArticleId(articleId);
        return JsonResult.ok(articleVO);
    }
}
